package cn.smbms.controller;

import cn.smbms.pojo.Provider;
import cn.smbms.pojo.User;
import cn.smbms.service.provider.ProviderService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

@Controller
@RequestMapping(value = "/provider")
public class ProviderController {

    private static Logger logger=Logger.getLogger(ProviderController.class);

    @Resource
    private ProviderService providerService;

    @RequestMapping(value = "/list")
    public String list(@RequestParam(value = "queryProName",required = false)String queryProName,
                       @RequestParam(value = "queryProCode",required = false)String queryProCode,
                       @RequestParam(value = "pageIndex",required = false)String pageIndex,
                       HttpServletRequest request){
        //创建一个分页辅助类对象
        PageSupport pageSupport=new PageSupport();

        //获取并设置总记录数
        pageSupport.setTotalCount(providerService.getProviderCount(queryProCode,queryProName ));
        //设置当前页码
        pageSupport.setCurrentPageNo(pageIndex==null?1:Integer.valueOf(pageIndex));

        //查询供应商信息并保存到pageSupport对象中
        pageSupport.setList(providerService.getProviderList(queryProCode, queryProName, pageSupport.getCurrentPageNo(), pageSupport.getPageSize()));

        //将pageSupport保存至requset中
        request.setAttribute("pageObj", pageSupport);

        return "providerlist";
    }

    @RequestMapping(value = "/toAddPager")
    public String toAddPager(){
        return "provideradd";
    }

    @RequestMapping(value = "/doAdd")
    public String doAddProvider(Provider provider,
                                HttpSession session,
                                HttpServletRequest request,
                                @RequestParam(value = "attachs",required = false) MultipartFile[]attachs){

        boolean flag=true;

        logger.debug("upload   attach:==============>"+attachs.length);

        for (int i = 0; i < attachs.length; i++) {

            MultipartFile attach=attachs[i];

            if (!attach.isEmpty()){
                String path=request.getSession().getServletContext().getRealPath(Constants.PROVIDER_PIC_PATH);

                //获取源文件名称
                String resourceName=attach.getName();

                //获取文件后缀名
                String suffix=attach.getOriginalFilename().toLowerCase();

                //支持上传的文件格式
                String[]fileFormat={"png","pneg","jpg","jpeg"};

                Integer maxSize=5000000;

                if(attach.getSize()<=maxSize){
                    if(!Arrays.asList(fileFormat).contains(suffix)){
                        //生成文件名
                        String fileName=System.currentTimeMillis()+RandomUtils.nextInt(0, 1000000)+(i>0?"_orgCodePicPath":"_companyLic")+".jpg";

                        //创建文件操作对象
                        File file=new File(path,fileName);

                        if (!file.exists()){
                            //创建当前目录及其所必须的父级目录
                            file.mkdirs();
                        }

                        try {
                            attach.transferTo(file);

                            if (i==0){
                                provider.setCompanyLicPicPath(fileName);
                            }else if(i==1){
                                provider.setOrgCodePicPath(fileName);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                            request.setAttribute("uploadError"+(i>0?"2":"1"), "文件上传失败！");
                            flag=false;
                        }
                    }else{
                        request.setAttribute("uploadError"+(i>0?"2":"1"), "文件格式不正确！");
                        flag=false;
                    }
                }else{
                    request.setAttribute("uploadError"+(i>0?"2":"1"), "文件大小不能超过500KB");
                    flag=false;
                }
            }
        }

        provider.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        provider.setCreationDate(new Date());

        if (providerService.addProvider(provider)){
            return "redirect:/provider/list";
        }

        return "redirect:/provider/toAddPager";
    }

    @RequestMapping(value = "/toAddPager2",method = RequestMethod.GET)
    public String toAddPager2(@ModelAttribute(value = "provider") Provider provider){
        return "provideradd2";
    }

    @RequestMapping(value = "/toAddPager2",method = RequestMethod.POST)
    public String doAddProvider2(@Valid Provider provider, BindingResult result, HttpSession session){

        if(result.hasErrors()){
            logger.debug("addProvider =======》"+result.hasErrors());

            return "provideradd2";
        }

        provider.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        provider.setCreationDate(new Date());

        if (providerService.addProvider(provider)){
            return "redirect:/provider/list";
        }

        return "redirect:/provider/toAddPager";
    }

    @RequestMapping(value = "/view/{id}")
    public String showDetail(@PathVariable Integer id, HttpServletRequest request){
        request.setAttribute("provider", providerService.getProviderById(id));

        return "providerview";
    }

    @RequestMapping(value = "/tomodify/{id}")
    public String toModify(@PathVariable Integer id, HttpServletRequest request){
        request.setAttribute("provider", providerService.getProviderById(id));

        return "providermodify";
    }

    @RequestMapping(value = "/domodify",method = RequestMethod.POST)
    public String doModify(Provider provider,HttpServletRequest request,HttpSession session){

        provider.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        provider.setModifyDate(new Date());

        if (providerService.modfiyProvider(provider)){
            return "redirect:/provider/list";
        }

        request.setAttribute("error", "修改失败！");

        return "provider/tomodify";
    }
}
